import { isUndefined } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import { createStoreApiMWRouter } from "../../middleware/store-api/storeOwnerChecker";
import pageMW from "../../middleware/pager";
import { isSearchTerm } from "../../bg-enums/searchTerm";
import {
  getAfterSaleBySerialNumber,
  listAfterSaleItemsForStore,
} from "../../service/afterSaleService";
const router = createStoreApiMWRouter();

// 获取门店的售后列表
router.get("/sto/:storeId/afterSales", pageMW, async (ctx: AppCTX, next) => {
  const { storeId } = ctx.params;
  const { userId, limit, offset, ts } = ctx;
  const { searchTerm, searchValue } = ctx.query;
  if (!isUndefined(searchTerm) && !isSearchTerm(searchTerm)) {
    ctx.throw(400, "invalid searchTerm");
  }
  const { total, items } = await listAfterSaleItemsForStore(
    {
      storeId,
      searchTerm,
      searchValue,
    },
    {
      limit,
      offset,
      ts,
    }
  );
  ctx.body = {
    total,
    rows: items,
  };
});

// 获取售后单详情(门店视角)
router.get(
  "/sto/:storeId/afterSale/:afterSaleSerialNumber",
  async (ctx: AppCTX, next) => {
    const { storeId, afterSaleSerialNumber } = ctx.params;
    const { userId } = ctx;

    const afterSale = await getAfterSaleBySerialNumber(afterSaleSerialNumber);
    if (isUndefined(afterSale)) {
      ctx.throw(400, "invalid afterSaleSerialNumber");
    }
    if (afterSale.storeId !== storeId) {
      ctx.throw(403, "no permit access to the aftersale");
    }

    ctx.body = afterSale;
  }
);

export default router;
